import { ComponentType } from 'react'
import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Text } from '@tarojs/components'
import FuIcon from '@/components/FuIcon'
import './index.scss'


type FuTabs = {
  list: Array<any>,
  showKey?: string,
  center?: boolean,
  active?: number,
  customStyle?: Object,
  itemStyle?: Object,
  scroll?: boolean,
  scrollCenter?: boolean,
  onChang?: (res: any) => {}
}


class FuTab extends Component<FuTabs> {

  state = {
    active: this.props.active || 0,
    actionStyle: {
      color: "#f00",
      borderBottom: "2px solid",
      borderColor: "#f00"
    },
    scrollLeft: 0
  }

  componentWillMount() { }

  componentWillReact() { }

  componentDidMount() { }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  render() {
    const {
      list,
      showKey = "title",
      customStyle = { height: "57px" },
      itemStyle = {},
      scroll,
      scrollCenter,
      onChang
    } = this.props;
    const { active, actionStyle, scrollLeft } = this.state;
    return (
      <ScrollView
        enable-flex
        className="fu-tab"
        scrollX={scroll}
        scroll-with-animation
        scroll-left={scrollLeft}
        style={customStyle}
      >
        {
          (list || []).map((item: any, index: number) => (
            <View
              key={index}
              onClick={(e) => {
                if (scrollCenter) {
                  const { currentTarget: { offsetLeft = 0 } } = e
                  const cellWidth = Math.floor(offsetLeft / index)
                  const left = offsetLeft - cellWidth * 2
                  this.setState({ active: index, scrollLeft: left }, () => {
                    onChang && onChang(list[index])
                  });
                } else {
                  this.setState({ active: index }, () => {
                    onChang && onChang(list[index])
                  });
                }
              }}
              className={"fu-tab-item " + (scroll ? " " : " fu-tab-item-nosrc")}
              style={active == index ? { ...actionStyle, ...itemStyle } : {}}
            >
              {item["icon"] ?
                <FuIcon
                  customStyle={active == index ?
                    { color: actionStyle.color, marginRight: "5px", ...itemStyle }
                    : { marginRight: "5px" }
                  }
                  name={item["icon"]} />
                : null
              }
              {item[showKey]}
            </View>
          ))
        }
      </ScrollView>
    )
  }
}

export default FuTab as ComponentType<FuTabs>
